{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "!pip install -q langgraph langchain-google-genai langchain-core\n",
        "\n",
        "import os\n",
        "from typing import TypedDict, Annotated, List, Dict, Any\n",
        "from langgraph.graph import StateGraph, END\n",
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "from langchain_core.messages import BaseMessage, HumanMessage, AIMessage\n",
        "import operator\n",
        "import json\n",
        "\n",
        "\n",
        "os.environ[\"GOOGLE_API_KEY\"] = \"Use Your Own API Key\"\n",
        "\n",
        "class AgentState(TypedDict):\n",
        "    messages: Annotated[List[BaseMessage], operator.add]\n",
        "    current_agent: str\n",
        "    research_data: dict\n",
        "    analysis_complete: bool\n",
        "    final_report: str\n",
        "\n",
        "llm = ChatGoogleGenerativeAI(model=\"gemini-1.5-flash\", temperature=0.7)"
      ],
      "metadata": {
        "id": "bTnK5SVFm0_u"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def simulate_web_search(query: str) -> str:\n",
        "    \"\"\"Simulated web search - replace with real API in production\"\"\"\n",
        "    return f\"Search results for '{query}': Found relevant information about {query} including recent developments, expert opinions, and statistical data.\"\n",
        "\n",
        "def simulate_data_analysis(data: str) -> str:\n",
        "    \"\"\"Simulated data analysis tool\"\"\"\n",
        "    return f\"Analysis complete: Key insights from the data include emerging trends, statistical patterns, and actionable recommendations.\"\n",
        "\n",
        "def research_agent(state: AgentState) -> AgentState:\n",
        "    \"\"\"Agent that conducts research on a given topic\"\"\"\n",
        "    messages = state[\"messages\"]\n",
        "    last_message = messages[-1].content\n",
        "\n",
        "    search_results = simulate_web_search(last_message)\n",
        "\n",
        "    prompt = f\"\"\"You are a research agent. Based on the query: \"{last_message}\"\n",
        "\n",
        "    Here are the search results: {search_results}\n",
        "\n",
        "    Conduct thorough research and gather relevant information. Provide structured findings with:\n",
        "    1. Key facts and data points\n",
        "    2. Current trends and developments\n",
        "    3. Expert opinions and insights\n",
        "    4. Relevant statistics\n",
        "\n",
        "    Be comprehensive and analytical in your research summary.\"\"\"\n",
        "\n",
        "    response = llm.invoke([HumanMessage(content=prompt)])\n",
        "\n",
        "    research_data = {\n",
        "        \"topic\": last_message,\n",
        "        \"findings\": response.content,\n",
        "        \"search_results\": search_results,\n",
        "        \"sources\": [\"academic_papers\", \"industry_reports\", \"expert_analyses\"],\n",
        "        \"confidence\": 0.88,\n",
        "        \"timestamp\": \"2024-research-session\"\n",
        "    }\n",
        "\n",
        "    return {\n",
        "        \"messages\": state[\"messages\"] + [AIMessage(content=f\"Research completed on '{last_message}': {response.content}\")],\n",
        "        \"current_agent\": \"analysis\",\n",
        "        \"research_data\": research_data,\n",
        "        \"analysis_complete\": False,\n",
        "        \"final_report\": \"\"\n",
        "    }"
      ],
      "metadata": {
        "id": "w7pQa211oDmA"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def analysis_agent(state: AgentState) -> AgentState:\n",
        "    \"\"\"Agent that analyzes research data and extracts insights\"\"\"\n",
        "    research_data = state[\"research_data\"]\n",
        "\n",
        "    analysis_results = simulate_data_analysis(research_data.get('findings', ''))\n",
        "\n",
        "    prompt = f\"\"\"You are an analysis agent. Analyze this research data in depth:\n",
        "\n",
        "    Topic: {research_data.get('topic', 'Unknown')}\n",
        "    Research Findings: {research_data.get('findings', 'No findings')}\n",
        "    Analysis Results: {analysis_results}\n",
        "\n",
        "    Provide deep insights including:\n",
        "    1. Pattern identification and trend analysis\n",
        "    2. Comparative analysis with industry standards\n",
        "    3. Risk assessment and opportunities\n",
        "    4. Strategic implications\n",
        "    5. Actionable recommendations with priority levels\n",
        "\n",
        "    Be analytical and provide evidence-based insights.\"\"\"\n",
        "\n",
        "    response = llm.invoke([HumanMessage(content=prompt)])\n",
        "\n",
        "    return {\n",
        "        \"messages\": state[\"messages\"] + [AIMessage(content=f\"Analysis completed: {response.content}\")],\n",
        "        \"current_agent\": \"report\",\n",
        "        \"research_data\": state[\"research_data\"],\n",
        "        \"analysis_complete\": True,\n",
        "        \"final_report\": \"\"\n",
        "    }\n",
        "\n",
        "\n",
        "def report_agent(state: AgentState) -> AgentState:\n",
        "    \"\"\"Agent that generates final comprehensive reports\"\"\"\n",
        "    research_data = state[\"research_data\"]\n",
        "\n",
        "    analysis_message = None\n",
        "    for msg in reversed(state[\"messages\"]):\n",
        "        if isinstance(msg, AIMessage) and \"Analysis completed:\" in msg.content:\n",
        "            analysis_message = msg.content.replace(\"Analysis completed: \", \"\")\n",
        "            break\n",
        "\n",
        "    prompt = f\"\"\"You are a professional report generation agent. Create a comprehensive executive report based on:\n",
        "\n",
        "    🔍 Research Topic: {research_data.get('topic')}\n",
        "    📊 Research Findings: {research_data.get('findings')}\n",
        "    🧠 Analysis Results: {analysis_message or 'Analysis pending'}\n",
        "\n",
        "    Generate a well-structured, professional report with these sections:\n",
        "\n",
        "    ## EXECUTIVE SUMMARY\n",
        "    [Provide a concise overview of key findings and recommendations]\n",
        "\n",
        "    ## KEY RESEARCH FINDINGS\n",
        "    [Detail the most important discoveries and data points]\n",
        "\n",
        "    ## ANALYTICAL INSIGHTS\n",
        "    [Present deep analysis, patterns, and trends identified]\n",
        "\n",
        "    ## STRATEGIC RECOMMENDATIONS\n",
        "    [Provide actionable recommendations with priority levels]\n",
        "\n",
        "    ## RISK ASSESSMENT & OPPORTUNITIES\n",
        "    [Identify potential risks and opportunities]\n",
        "\n",
        "    ## CONCLUSION & NEXT STEPS\n",
        "    [Summarize and suggest follow-up actions]\n",
        "\n",
        "    Make the report professional, data-driven, and actionable.\"\"\"\n",
        "\n",
        "    response = llm.invoke([HumanMessage(content=prompt)])\n",
        "\n",
        "    return {\n",
        "        \"messages\": state[\"messages\"] + [AIMessage(content=f\"📄 FINAL REPORT GENERATED:\\n\\n{response.content}\")],\n",
        "        \"current_agent\": \"complete\",\n",
        "        \"research_data\": state[\"research_data\"],\n",
        "        \"analysis_complete\": True,\n",
        "        \"final_report\": response.content\n",
        "    }"
      ],
      "metadata": {
        "id": "2_taSKtNoJNY"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def should_continue(state: AgentState) -> str:\n",
        "    \"\"\"Determine which agent should run next based on current state\"\"\"\n",
        "    current_agent = state.get(\"current_agent\", \"research\")\n",
        "\n",
        "    if current_agent == \"research\":\n",
        "        return \"analysis\"\n",
        "    elif current_agent == \"analysis\":\n",
        "        return \"report\"\n",
        "    elif current_agent == \"report\":\n",
        "        return END\n",
        "    else:\n",
        "        return END\n",
        "\n",
        "workflow = StateGraph(AgentState)\n",
        "\n",
        "workflow.add_node(\"research\", research_agent)\n",
        "workflow.add_node(\"analysis\", analysis_agent)\n",
        "workflow.add_node(\"report\", report_agent)\n",
        "\n",
        "workflow.add_conditional_edges(\n",
        "    \"research\",\n",
        "    should_continue,\n",
        "    {\"analysis\": \"analysis\", END: END}\n",
        ")\n",
        "\n",
        "workflow.add_conditional_edges(\n",
        "    \"analysis\",\n",
        "    should_continue,\n",
        "    {\"report\": \"report\", END: END}\n",
        ")\n",
        "\n",
        "workflow.add_conditional_edges(\n",
        "    \"report\",\n",
        "    should_continue,\n",
        "    {END: END}\n",
        ")\n",
        "\n",
        "workflow.set_entry_point(\"research\")\n",
        "\n",
        "app = workflow.compile()\n",
        "\n",
        "def run_research_assistant(query: str):\n",
        "    \"\"\"Run the complete research workflow\"\"\"\n",
        "    initial_state = {\n",
        "        \"messages\": [HumanMessage(content=query)],\n",
        "        \"current_agent\": \"research\",\n",
        "        \"research_data\": {},\n",
        "        \"analysis_complete\": False,\n",
        "        \"final_report\": \"\"\n",
        "    }\n",
        "\n",
        "    print(f\"🔍 Starting Multi-Agent Research on: '{query}'\")\n",
        "    print(\"=\" * 60)\n",
        "\n",
        "    current_state = initial_state\n",
        "\n",
        "    print(\"🤖 Research Agent: Gathering information...\")\n",
        "    current_state = research_agent(current_state)\n",
        "    print(\"✅ Research phase completed!\\n\")\n",
        "\n",
        "    print(\"🧠 Analysis Agent: Analyzing findings...\")\n",
        "    current_state = analysis_agent(current_state)\n",
        "    print(\"✅ Analysis phase completed!\\n\")\n",
        "\n",
        "    print(\"📊 Report Agent: Generating comprehensive report...\")\n",
        "    final_state = report_agent(current_state)\n",
        "    print(\"✅ Report generation completed!\\n\")\n",
        "\n",
        "    print(\"=\" * 60)\n",
        "    print(\"🎯 MULTI-AGENT WORKFLOW COMPLETED SUCCESSFULLY!\")\n",
        "    print(\"=\" * 60)\n",
        "\n",
        "    final_report = final_state['final_report']\n",
        "    print(f\"\\n📋 COMPREHENSIVE RESEARCH REPORT:\\n\")\n",
        "    print(final_report)\n",
        "\n",
        "    return final_state"
      ],
      "metadata": {
        "id": "ntZK8UzioVRO"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "if __name__ == \"__main__\":\n",
        "    print(\"🚀 Advanced LangGraph Multi-Agent System Ready!\")\n",
        "    print(\"🔧 Remember to set your GOOGLE_API_KEY!\")\n",
        "\n",
        "    example_queries = [\n",
        "        \"What are the latest trends in artificial intelligence for 2024?\",\n",
        "        \"Impact of renewable energy on global markets\",\n",
        "        \"Future of remote work post-pandemic\"\n",
        "    ]\n",
        "\n",
        "    print(f\"\\n💡 Example queries you can try:\")\n",
        "    for i, query in enumerate(example_queries, 1):\n",
        "        print(f\"  {i}. {query}\")\n",
        "\n",
        "    print(f\"\\n🎯 Usage: run_research_assistant('Your research question here')\")\n",
        "\n",
        "    result = run_research_assistant(\"What are emerging trends in sustainable technology?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ErI2Imvvli5S",
        "outputId": "47cb4e16-25a1-44cc-f5e4-a3fe84c3e640"
      },
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🚀 Advanced LangGraph Multi-Agent System Ready!\n",
            "🔧 Remember to set your GOOGLE_API_KEY!\n",
            "\n",
            "💡 Example queries you can try:\n",
            "  1. What are the latest trends in artificial intelligence for 2024?\n",
            "  2. Impact of renewable energy on global markets\n",
            "  3. Future of remote work post-pandemic\n",
            "\n",
            "🎯 Usage: run_research_assistant('Your research question here')\n",
            "🔍 Starting Multi-Agent Research on: 'What are emerging trends in sustainable technology?'\n",
            "============================================================\n",
            "🤖 Research Agent: Gathering information...\n",
            "✅ Research phase completed!\n",
            "\n",
            "🧠 Analysis Agent: Analyzing findings...\n",
            "✅ Analysis phase completed!\n",
            "\n",
            "📊 Report Agent: Generating comprehensive report...\n",
            "✅ Report generation completed!\n",
            "\n",
            "============================================================\n",
            "🎯 MULTI-AGENT WORKFLOW COMPLETED SUCCESSFULLY!\n",
            "============================================================\n",
            "\n",
            "📋 COMPREHENSIVE RESEARCH REPORT:\n",
            "\n",
            "## EXECUTIVE SUMMARY\n",
            "\n",
            "The global sustainable technology market is experiencing rapid, exponential growth driven by environmental concerns, stringent regulations, and rising consumer demand.  Key trends include the dominance of renewable energy, the emergence of green hydrogen, circular economy solutions, smart grid technologies, and sustainable transportation.  While significant challenges remain, including high upfront costs and scalability issues, the potential benefits are substantial.  This report recommends prioritizing investments in carbon pricing mechanisms, R&D for key technologies (green hydrogen, energy storage, CCUS), robust regulatory frameworks, and smart grid infrastructure.  Addressing public awareness and fostering public-private partnerships are also crucial for successful transition to a sustainable future.\n",
            "\n",
            "## KEY RESEARCH FINDINGS\n",
            "\n",
            "* **Market Growth:** The global sustainable technology market is expanding rapidly, with significant investment flowing into renewable energy, green building materials, and waste management.\n",
            "* **Technological Advancements:**  Progress in renewable energy (solar, wind, geothermal), green hydrogen production, circular economy solutions, smart grids, sustainable transportation, sustainable building materials, precision agriculture, and carbon capture, utilization, and storage (CCUS) are driving the transition.\n",
            "* **Alignment with SDGs:** Sustainable technologies are crucial for achieving the UN Sustainable Development Goals (SDGs), particularly SDG 7, 9, and 13.\n",
            "* **Challenges:** High upfront costs, technological limitations, scalability issues, and a lack of public awareness are hindering widespread adoption.\n",
            "\n",
            "\n",
            "## ANALYTICAL INSIGHTS\n",
            "\n",
            "Analysis reveals several interconnected patterns:\n",
            "\n",
            "* **Exponential Growth:** The market's growth is fueled by a synergistic effect of heightened environmental awareness, stricter regulations, and increased investor confidence.\n",
            "* **Technological Interdependence:**  Trends are interconnected; for example, renewable energy relies on advancements in energy storage.\n",
            "* **Data-Driven Optimization:** Data analytics and AI are optimizing resource use across various sectors.\n",
            "* **Shifting Paradigms:**  The transition from linear to circular economy models is a fundamental shift requiring systemic changes.\n",
            "\n",
            "Comparative analysis with industry standards suggests that while progress is being made in areas like renewable energy and EVs, significant acceleration is needed to meet global decarbonization targets.  CCUS deployment, in particular, lags behind other areas.\n",
            "\n",
            "\n",
            "## STRATEGIC RECOMMENDATIONS\n",
            "\n",
            "**High Priority:**\n",
            "\n",
            "1. **Implement robust carbon pricing mechanisms:** This creates a strong economic incentive for adopting sustainable technologies.\n",
            "2. **Increase public investment in R&D:** Focus on green hydrogen, advanced energy storage, and scalable CCUS solutions.\n",
            "3. **Develop and implement clear regulatory frameworks:** This reduces uncertainty and encourages investment.\n",
            "4. **Invest heavily in smart grid infrastructure:**  This is crucial for efficient renewable energy integration.\n",
            "\n",
            "**Medium Priority:**\n",
            "\n",
            "1. **Promote public awareness campaigns:** Educate consumers and encourage behavioral change.\n",
            "2. **Foster public-private partnerships:**  Collaborate on developing and deploying solutions.\n",
            "3. **Develop standardized environmental impact metrics:** This enables better comparison and decision-making.\n",
            "\n",
            "**Low Priority (but important long-term):**\n",
            "\n",
            "1. **Invest in research on equitable access to sustainable technologies:** Ensure benefits are shared broadly.\n",
            "2. **Explore innovative financing mechanisms:** Facilitate access to capital for sustainable technology startups in developing countries.\n",
            "\n",
            "\n",
            "## RISK ASSESSMENT & OPPORTUNITIES\n",
            "\n",
            "**Risks:** Technological limitations, high upfront costs, scalability challenges, policy uncertainty, and public acceptance issues hinder widespread adoption.\n",
            "\n",
            "**Opportunities:**  First-mover advantages for businesses, job creation, improved public health, enhanced resource security, and new market creation present significant potential.\n",
            "\n",
            "\n",
            "## CONCLUSION & NEXT STEPS\n",
            "\n",
            "The transition to a sustainable future requires a concerted effort from governments, businesses, researchers, and individuals.  The recommendations outlined in this report provide a roadmap for accelerating the adoption of sustainable technologies.  Further research should focus on continuously monitoring the effectiveness of these technologies, addressing emerging challenges, and ensuring equitable access to the benefits of sustainable development.  Regular monitoring of market trends, technological advancements, and policy developments is essential for adapting strategies and maximizing the impact of investments in sustainable technologies.  A dedicated task force should be established to oversee the implementation of these recommendations and track progress against established benchmarks.\n"
          ]
        }
      ]
    }
  ]
}